var isUpLoadImg = "NO";
window.addEventListener('DOMContentLoaded', function () {
    var avatar = document.getElementById('avatar');
    var image = document.getElementById('image');
    var input = document.getElementById('input');
    var $progress = $('.progress');
    var $progressBar = $('.progress-bar');
    var $alert = $('.alert');
    var $modal = $('#modal');
    var cropper;

    $('[data-toggle="tooltip"]').tooltip();

    input.addEventListener('change', function (e) {
        var files = e.target.files;
        var done = function (url) {
            input.value = '';
            image.src = url;
            $alert.hide();
            $modal.modal('show');
        };
        var reader;
        var file;
        var url;

        if (files && files.length > 0) {
            file = files[0];

            if (URL) {
                done(URL.createObjectURL(file));
            } else if (FileReader) {
                reader = new FileReader();
                reader.onload = function (e) {
                    done(reader.result);
                };
                reader.readAsDataURL(file);
            }
        }
    });

    $modal.on('shown.bs.modal', function () {
        cropper = new Cropper(image, {
            aspectRatio: 1,
            viewMode: 3,
        });
    }).on('hidden.bs.modal', function () {
        cropper.destroy();
        cropper = null;
    });

    document.getElementById('crop').addEventListener('click', function () {
        var type = $("#valueType").val();
        var value = $("#value").val();
        var contactDetails = type + value;
        var info = $("#info").val();
        if (type === "QQ：") {
            if (!/^[1-9][0-9]{4,10}$/.test(value)) {
                cocoMessage.error(3000, "请输入正确的QQ号", function () {
                    //回调函数
                });
                return;
            }
        } else if (type === "微信号：") {
            if (!/^[a-zA-Z]{1}[-_a-zA-Z0-9]{5,19}$/.test(value)) {
                cocoMessage.error(3000, "请输入正确的微信号", function () {
                    //回调函数
                });
                return;
            }
        } else if (type === "手机号：") {
            if (!/^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/.test(value)) {
                cocoMessage.error(3000, "请输入正确的手机号", function () {
                    //回调函数
                });
                return;
            }
        }
        if (contactDetails == "" || info == "") {
            cocoMessage.error(3000, "请将信息填写完整！", function () {
                //回调函数
            });
            return;
        }
        isUpLoadImg="YES";
        var initialAvatarURL;
        var canvas;

        $modal.modal('hide');

        if (cropper) {
            canvas = cropper.getCroppedCanvas({
                width: 500,
                height: 500,
            });
            initialAvatarURL = avatar.src;
            avatar.src = canvas.toDataURL();
            $progress.show();
            canvas.toBlob(function (blob) {
                var form = new FormData();
                form.append("self_img", blob, "-uploadBy-" + window.localStorage.u_id + ".jpg");
                form.append("u_id", window.localStorage.u_id);
                $.ajax({
                    url: '/paper_file_handle',
                    type: "post",
                    data: form,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        if (res.status == "handle_success" || res.status == "no_self_imgs") {
                            cocoMessage.success(1000, "图片上传成功", function () {
                                upload_num = 0;
                                //回调函数
                                putTip(res.data)
                            });
                        }
                        else if(res.status == "over_max_lauch_nums")
                        {
                            cocoMessage.error(2000, "当日投递纸条数量已达到最大限制次数", function () {
                                //回调函数
                                location.reload()
                            });
                        }
                        else
                        {
                            cocoMessage.error(2000, "图片上传失败，请重新上传", function () {
                                //回调函数
                            });
                        }
                    }
                })
            })
        }
    });
});

//投放纸条
function putTip(imgs) {
    var type = $("#valueType").val();
    var value = $("#value").val();
    var contactDetails = type + value;
    var info = $("#info").val();
    if (type === "QQ：") {
        if (!/^[1-9][0-9]{4,10}$/.test(value)) {
            cocoMessage.error(3000, "请输入正确的QQ号", function () {
                //回调函数
            });
            return;
        }
    } else if (type === "微信号：") {
        if (!/^[a-zA-Z]{1}[-_a-zA-Z0-9]{5,19}$/.test(value)) {
            cocoMessage.error(3000, "请输入正确的微信号", function () {
                //回调函数
            });
            return;
        }
    } else if (type === "手机号：") {
        if (!/^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/.test(value)) {
            cocoMessage.error(3000, "请输入正确的手机号", function () {
                //回调函数
            });
            return;
        }
    }
    if (contactDetails == "" || info == "") {
        cocoMessage.error(3000, "请将信息填写完整！", function () {
            //回调函数
        });
        return;
    }
    $.ajax({
        url: "/paper_into_box",
        type: 'post',
        data: {
            'contactdata': contactDetails,
            'selfinfo': info,
            'userid': window.localStorage.u_id,
            "selfImgs": isUpLoadImg === "NO" ? "NO_FILE_UPLOAD" : imgs,
            'token': window.localStorage.mkdir_fbi_bb
        },
        success: function (res) {
            if (res.status === "over_max_lauch_nums") {
                empty()
                cocoMessage.error(3000, "当日投递纸条数量已达到最大限制次数", function () {
                    //回调函数
                });
                return;
            } else if (res.status === 'database_error') {
                empty()
                cocoMessage.error(3000, "出现异常，请重试！", function () {
                    //回调函数
                });
                return;
            } else if (res.status === 'handle_success') {
                empty()
                cocoMessage.success(3000, "投递成功,今日可抽取次数+2!", function () {
                    //回调函数
                });
                return;
            } else {
                empty()
                cocoMessage.error(3000, "出现异常，请重试！", function () {
                    //回调函数
                });
                return;
            }
        }
    })
    $("#putTip").modal('hide');
    return false;
}

//清空表单元素
function empty() {
    $("#info").val("")
    $("#value").val("")
}